package java8.stream;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * @author Cheng Jun
 * Description: jdk 1.8 并行流的学习
 * @version 1.0
 * @date 2020/7/13 9:32
 */
public class ParallelStreamExample {

    public static void main(String[] args) throws InterruptedException {
        Collection<String> nameCollection = testParallelStream();
        System.out.println(nameCollection.size());
        nameCollection.forEach(name -> {
            System.out.println(name);
            System.out.println("sign");
        });

        // Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
        // List<Integer> listOfIntegers =
        //         new ArrayList<>(Arrays.asList(intArray));
        // List<Integer> parallelStorage = new ArrayList<>();
        // // List<Integer> parallelStorage = Collections.synchronizedList(new ArrayList<>());
        // long count = listOfIntegers
        //         .parallelStream()
        //         // Don't do this! It uses a stateful lambda expression.
        //         .map(e -> {
        //             parallelStorage.add(e);
        //             return e;
        //         }).count();
        // System.out.println(count);
        // parallelStorage
        //         .stream()
        //         .forEachOrdered(e -> System.out.print(e + " "));
        // System.out.println();
        // // System.out.println("Sleep 2 sec");
        // TimeUnit.SECONDS.sleep(2);
        // parallelStorage
        //         .stream()
        //         .forEachOrdered(e -> System.out.print(e + " "));

    }

    private static Collection<String> testParallelStream() {
        Set<String> nameSet = new HashSet<>();
        // Collection<String> collection = new HashSet<>();
        Collection<String> collection = Collections.synchronizedSet(new HashSet<>());
        for (int i = 0; i < 1000; i++) {
            nameSet.add("cj" + i);
        }
        // 并行流处理，需要保证接受处理结果的集合的 synchronized
        nameSet.parallelStream().forEach(name -> {
            collection.add(name);
        });
        System.out.println(collection.size());
        return collection;
    }
}
